package cn.edu.zut.hhr.handler;

import cn.edu.zut.hhr.entity.User;
import cn.edu.zut.hhr.utils.SnowflakeIdUtil;
import cn.edu.zut.hhr.utils.UserUtil;
import cn.edu.zut.hhr.vo.RestResponse;
import common.log.scholar_of_yore.service.CommonLogClient;
import common.log.scholar_of_yore.service.LogTemplate;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Log4j2
@ControllerAdvice
public class AllExceptionHandler {

    @Resource
    private LogTemplate logTemplate;

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public RestResponse exceptionHandler(HttpServletRequest req, Exception e){
        e.printStackTrace();
        StringBuilder sb = new StringBuilder();
        long logId = SnowflakeIdUtil.nextId();
        sb.append("====================log start====================");
        sb.append("servletPath: "+req.getServletPath());
        sb.append("method: "+req.getMethod());
        User user = UserUtil.currentUser();
        if(user != null){
            sb.append("username: "+user.getId().toString());
            sb.append("name: "+user.getName());
        }
        sb.append("exception: "+e.getMessage());
        sb.append("====================log end======================");
        logTemplate.error(String.valueOf(logId),"zut.hhr.blog",sb.toString());
        return RestResponse.fail(500,"服务器内部异常,logId="+logId,e);
    }

}
